//
//  WBRefreshControl.swift
//  01- 搭建框架
//
//  Created by apple on 15/10/22.
//  Copyright © 2015年 任伟. All rights reserved.
//

import UIKit

/// 箭头刷新控件偏移量
private let WBRefreshControlOffset: CGFloat = -60

/// 自定义刷新控件 - 负责处理刷新逻辑
class WBRefreshControl: UIRefreshControl {
    
    /// MARK: -重写系统的方法
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopAnimation()
    }
    
    override func beginRefreshing() {
        super.beginRefreshing()
        refreshView.startAnimation()
    }
    
    /// MARK: -KVO 监听方法
    /// 箭头旋转标记
    private var rotateFlag = false
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0 {
            return
        }
        
        // 判断是否在刷新
        if refreshing {
        refreshView.startAnimation()
            return
        }
        
        if frame.origin.y < WBRefreshControlOffset && !refreshView.rotateFlag {
            //print("反过来")
            refreshView.rotateFlag = true
        } else if frame.origin.y >= WBRefreshControlOffset && refreshView.rotateFlag {
            //print("转过去")
            refreshView.rotateFlag = false
        }

        
        //print(frame)
    }
    
    /// MARK: -构造函数
    override init() {
        super.init()
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
    }
    
    private func setupUI() {
        
        addSubview(refreshView)
        
        // 自动布局
        refreshView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
            make.centerY.equalTo(self.snp_centerY)
            make.size.equalTo(refreshView.bounds.size)
        }
        
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            // 注册监听
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }
    
    // 取消监听
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    
    /// 懒加载控件
    private lazy var refreshView = WBRefreshView.refreshView()

}

/// 刷新视图 - 负责处理`动画显示`
class WBRefreshView: UIView {
    
    /// 旋转标记
    var rotateFlag = false {
        didSet {
        
            rotateTipIcon()
        }
    }
    
    @IBOutlet weak var loadingIconView: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipIconView: UIImageView!
    /// 懒加载 XIB
    class func refreshView() -> WBRefreshView {
    
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
        
        return nib.instantiateWithOwner(nil, options: nil).last as! WBRefreshView
    }
    
    private func rotateTipIcon() {
        
        var angle = CGFloat(M_PI)
        angle += rotateFlag ? -0.0000001 : 0.0000001
        
        UIView.animateWithDuration(0.5) { () -> Void in
            
            self.tipIconView.transform = CGAffineTransformRotate(self.tipIconView.transform, CGFloat(angle))
        }
    }
    
    /// 开始动画
    private func startAnimation() {
        
        tipView.hidden = true
        
        // 判断动画是否已经被添加
        let key = "transform.rotation"
        if loadingIconView.layer.animationForKey(key) != nil {
            return
        }
    
        //print("加载动画播放")
        
        let anim = CABasicAnimation(keyPath:key)
        
        anim.toValue = 2 * M_PI
        
        anim.repeatCount = MAXFLOAT
        
        anim.duration = 0.5
        
        loadingIconView.layer.addAnimation(anim, forKey: nil)
    }
    
    ///停止动画
    private func stopAnimation() {
        
        tipView.hidden = false
        
        loadingIconView.layer.removeAllAnimations()
    }
}
